<template>
  <div style="width: 100%; height: 0">
    <!-- {{ tableTaskList }} -->
    <!-- -->
    <el-table :ref="'subTask'"
              style="width: 100%"
              :data="tableTaskList"
              :expand-row-keys="expandRowKeys.map(item => item)"
              :no-hover="true"
              row-key="projectId"
              @expand-change="setExpandRowKeys"
              :isdrag="true">
      <el-table-column type="expand">
        <template slot-scope="props">
          <div class="ui-ml10">
            <!-- {{ props.row.data.witnessSubTaskInfoList.result }} -->
            <!--  -->
            <!-- <el-button
							type="primary"
							size="default"
							@click="toggleSelection(multipleSubTaskSelection, props.$index)"
							>选中</el-button
						> -->
            <!-- -->
            <!-- {{ props.row.data.witnessTaskId }} :key="props.row.data.witnessTaskId"-->
            <!--
							@selection-change="handleSubTaskSelectionChangeFn" -->
            <!-- {{ props.row.bidsectionInfoList }} -->
            <el-table

              :ref="'multipleTable_' + props.$index"
              :key="'multipleTable_' + props.$index"
              style="width: 98%"
              :data="props.row.bidsectionInfoList"
              :merge-columns="mergeColumns"
              border
              :isdrag="true"
              :no-hover="true"
              :header-cell-style="{ background: '#6486C6', color: '#FFFFFF' }"
            >
              <el-table-column prop="bidSectionName" label="标段名称" min-width="115" />
              <el-table-column prop="bidSectionCode" label="标段编号" min-width="115" />
              <el-table-column prop="bidOpenStartTime" label="开标时间" min-width="112" max-width="150">
                <template slot-scope="scope">
                  {{ formatDateFn(scope.row.bidOpenStartTime, "yyyy-MM-dd HH:mm") }}
                </template>
              </el-table-column>
              <el-table-column prop="openAddress" label="开标室" width="80" />
              <el-table-column prop="evaluationAddress" label="评标室" width="80" />
              <el-table-column prop="witnessLinkCode" label="见证阶段" width="80">
                <template slot-scope="scope">
                  {{ scope.row.witnessSubTaskName }}
                  <!-- {{ props.row.witnessLinkCode }}
                  {{ props.row.industryType }} -->
                  <!-- {{ witnessLinkCodeFn(scope.row.witnessLinkCode, props.row.industryType) }} -->
                </template>
              </el-table-column>
              <template v-if="witnessLinkCode === 'witnessing' || witnessLinkCode === 'stopWitness'">
                <el-table-column prop="witnessStartTime" label="见证开始时间" min-width="84" max-width="150">
                  <template slot-scope="scope">
                    {{ formatDateFn(scope.row.witnessStartTime, "yyyy-MM-dd HH:mm") }}
                  </template>
                </el-table-column>
                <el-table-column prop="exceptionTip" label="异常提醒" width="95">
                  <template slot-scope="scope">
                    {{ scope.row.exceptionTip }}
                    <i :class="scope.row.exceptionTip === '无异常' ? '' : 'el-icon-warning font-orange'" />
                  </template>
                </el-table-column>
                <el-table-column prop="witnessAllocateUserName" label="任务来源" min-width="90" />
              </template>
              <template v-if="witnessLinkCode === 'haveWitnessed'">
                <el-table-column prop="witnessStartTime" label="见证开始时间" min-width="84" max-width="150">
                  <template slot-scope="scope">
                    {{ formatDateFn(scope.row.witnessStartTime, "yyyy-MM-dd HH:mm") }}
                  </template>
                </el-table-column>
                <el-table-column prop="witnessEndTime" label="见证结束时间" min-width="84" max-width="150">
                  <template slot-scope="scope">
                    {{ formatDateFn(scope.row.witnessEndTime, "yyyy-MM-dd HH:mm") }}
                  </template>
                </el-table-column>
                <el-table-column prop="witnessResult" label="见证结果" width="95">
                  <template slot-scope="scope">
                    <template v-if="scope.row.witnessResult === '无异常'">
                      <span class="result-icon-container normal">
                        <i class="el-icon-circle-check font-green font12 ui-mr5" />
                        {{ scope.row.witnessResult }}
                      </span>
                    </template>
                    <template v-else>
                      <span style="result-icon-container unnormal">
                        <i class="el-icon-warning-outline font-orange font12 ui-mr5" />
                        {{ scope.row.witnessResult }}
                      </span>
                    </template>
                  </template>
                </el-table-column>
              </template>
              <template v-if="witnessLinkCode === 'toWitness'">
                <el-table-column prop="pushDataStatus" label="交易数据状态" width="120">
                  <template slot-scope="scope">
                    <i :class="buildDataStatus(scope.row.pushDataStatus)" />
                    <span>{{ scope.row.pushDataStatus }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="witnessAllocateUserName" label="任务来源" min-width="100" />
              </template>
              <el-table-column prop="witnessSubTaskAllocateTime" label="分配时间" min-width="84" max-width="150">
                <template slot-scope="scope">
                  {{ formatDateFn(scope.row.witnessSubTaskAllocateTime, "yyyy-MM-dd HH:mm") }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="230">
                <template slot-scope="scope">
                  <!-- {{witnessLinkCode}} -->
                  <!-- 见证中 witnessing；暂停见证 stopWitness；待见证 toWitness；已完成 haveWitnessed  -->
                  <template v-if="witnessLinkCode !== 'haveWitnessed'">
                    <el-button
                      v-if="witnessLinkCode === 'witnessing' || witnessLinkCode === 'stopWitness'"
                      type="text"
                      size="default"
                      @click="enterClickFn(scope)"
                    >
                      进入见证
                    </el-button>
                    <el-button
                      v-if="witnessLinkCode === 'toWitness'"
                      type="text"
                      size="default"
                      @click="startClickFn(scope)"
                    >
                      开始见证
                    </el-button>
                    <el-button
                      type="text"
                      size="default"
                      @click="allocateUserClickFn(scope, props)"
                    >
                      移交见证
                    </el-button>
                    <el-button
                      v-show="false"
                      v-if="witnessLinkCode === 'witnessing'"
                      :disabled="witnessLinkCode === 'stopWitness'"
                      type="text"
                      size="default"
                      @click="finishWitnessFn(scope, props)"
                    >
                      结束见证
                    </el-button>
                  </template>
                  <template v-else>
                    <!-- 我的见证 已完成 -->
                    <el-button type="text" size="default" @click="handleClickWitnessRecordFn(scope, props)">
                      查看见证记录
                    </el-button>
                    <!-- {{ scope.row.pageOpers }} -->
                    <!-- v-if="scope.row.pageOpers.length" -->
                    <el-button
                      v-if="pageOpersFn('OPERATE_VIEW_WITNESS_ATTACHMENT', scope.row.pageOpers)"
                      type="text"
                      size="default"
                      @click="handleClickAttachment(scope, props)"
                    >
                      附件
                      <!-- {{ scope.row.pageOpers[0].title }} -->
                    </el-button>
                    <!--  -->
                    <!-- 1111 -->
                    <el-button
                      v-if="pageOpersFn('OPERATE_VIEW_WITNESS_VIDEO', scope.row.pageOpers)"
                      type="text"
                      @click="openMediaFn(scope.row, props)"
                    >
                      查看视频
                    </el-button>
                  </template>
                  <!-- {{ scope.row.witnessSubTaskStatusEnum }}
                  {{ scope.row.pageOpers }}
                  {{ witnessLinkCode }} -->
                  <el-button
                    v-if="
                      witnessLinkCode === 'stopWitness' ||
                      witnessLinkCode === 'witnessing' ||
                      witnessLinkCode === 'haveWitnessed'
                    "
                    :disabled="!pageOpersFn('OPERATE_STOP_WITNESS_RECORD', scope.row.pageOpers)"
                    type="text"
                    size="default"
                    @click="stopRecordFn(scope, props)"
                  >
                    暂停记录
                  </el-button>
                  <!-- {{witnessLinkCode}} -->
                  <!-- -->
                  <!-- {{ scope.row.pageOpers }} -->
                  <el-button
                    v-if="witnessLinkCode === 'haveWitnessed'"
                    :disabled="!pageOpersFn('OPERATE_CANCEL_FINISHED', scope.row.pageOpers)"
                    type="text"
                    size="default"
                    @click="revokeWitnessFn(scope, props)"
                  >
                    撤销
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
      </el-table-column>
      <el-table-column type="index" :index="indexFn" align="center" label="序号" width="50" />
      <el-table-column prop="projectName" label="项目名称" min-width="160">
        <!-- <template slot-scope="scope">
          <span class="task-tag">
            <span :class="['', scope.row.data.witnessSubTaskStatusEnum]">
              {{
                witnessSubTaskStatusFn(scope.row.data.witnessSubTaskStatusEnum)
              }}
            </span></span
          >
        </template> -->
      </el-table-column>
      <el-table-column prop="projectCode" label="项目编号" min-width="180" />
      <el-table-column prop="industryType" label="行业类别" min-width="150">
        <template slot-scope="scope">
          {{ industryFn(scope.row.industryType) }}/{{ subIndustryFn(scope.row.industry) }}
        </template>
      </el-table-column>
      <el-table-column prop="tenderMode" label="交易方式" min-width="150">
        <template slot-scope="scope">
          {{ industryTypeFn(scope.row.tenderMode, scope.row.industryType) }}
        </template>
      </el-table-column>
      <el-table-column prop="qualificationExamMethod" label="资审方式" min-width="150">
        <template slot-scope="scope">
          {{ qualificationExamMethodFn(scope.row.qualificationExamMethod) }}
        </template>
      </el-table-column>
      <el-table-column prop="businessUnit" label="业务部门" min-width="100" show-overflow-tooltip />
      <el-table-column prop="operateUserName" label="经办人" min-width="80" show-overflow-tooltip />
      <el-table-column label="操作" align="center" header-align="center" width="320">
        <!-- 2.子任务按钮显示逻辑：
待分配：【分配见证人】
待见证：【更改见证人】
见证中：【进入见证】【更改见证人】
待审核：【审核见证记录】
已完成：【查看见证记录】 -->
        <!-- v-if="scope.row.type == 'start'" -->
        <template slot-scope="scope">
          <el-button type="text" size="default" @click="handleViewDetailFn(scope.row.projectId)">项目详情</el-button>

          <!-- 项目级别开始见证 -->
          <template v-if="witnessLinkCode === 'toWitness'">
            <!-- 开标开始见证 -->
            <el-button
              v-if="scope.row.START_ALL_KB"
              type="text"
              size="default"
              @click="startAllClickFn('KB', scope.row)"
            >开标开始见证
            </el-button>
            <!-- 评标开始见证 -->
            <el-button
              v-if="scope.row.START_ALL_PB"
              type="text"
              size="default"
              @click="startAllClickFn('PB', scope.row)"
            >评标开始见证
            </el-button>
            <!-- 清标开始见证 -->
            <el-button
              v-if="scope.row.START_ALL_QB"
              type="text"
              size="default"
              @click="startAllClickFn('QB', scope.row)"
            >清标开始见证
            </el-button>
          </template>
          <!-- 项目级别结束见证 -->
          <template v-if="witnessLinkCode === 'witnessing'">
            <!-- 开标结束见证 -->
            <el-button
              v-if="scope.row.START_ALL_KB"
              type="text"
              size="default"
              @click="finishAllClickFn('KB', scope.row)"
            >开标结束见证
            </el-button>
            <!-- 清标结束见证 -->
            <el-button
              v-if="scope.row.START_ALL_QB"
              type="text"
              size="default"
              @click="finishAllClickFn('QB', scope.row)"
            >清标结束见证
            </el-button>
            <!-- 评标结束见证 -->
            <template v-if="scope.row.START_ALL_PB">
              <gzOverWitness @over="(closeFun) => finishAllClickFn('PB', scope.row, closeFun)"
                             :id="scope.row.projectId"
                             class="finish-all-click"
                             operationType="PROJECT" />
              <gzAddReviewTime type="OBJECT" :id="scope.row.projectId" />
            </template>
          </template>
          <!-- 查看见证报告 -->
          <template v-if="witnessLinkCode === 'haveWitnessed' && scope.row.START_ALL_JZBG">
            <el-button
              type="text"
              size="default"
              @click="goToWitnessReport(scope.row)"
            >见证报告
            </el-button>
          </template>

          <!-- 项目级别移交见证-->
          <template v-if="witnessLinkCode === 'witnessing' || witnessLinkCode === 'toWitness'">
            <el-button
              style="margin-left: 10px"
              type="text"
              size="default"
              @click="allocateAllUserClickFn(scope.row)"
            >
              移交见证
            </el-button>
          </template>
          <!-- <el-button
            v-if="
              pageOpersFn(
                'OPERATE_VIEW_SUB_WITNESS_TASK_RECORD',
                scope.row.pageOpers
              )
            "
            type="text"
            size="default"
            @click="recordShowFn(scope)"
            >查看见证记录</el-button
          >
          <el-button
            v-if="
              pageOpersFn('OPERATE_APPROVE_WITNESS_RECORD', scope.row.pageOpers)
            "
            type="text"
            size="default"
            @click="recordClickFn(scope)"
            >审核见证记录</el-button
          >
          <el-button
            v-if="
              pageOpersFn('OPERATE_UPDATE_WITNESS_USER', scope.row.pageOpers)
            "
            type="text"
            size="default"
            @click="updateClickFn(scope)"
            >更改见证人</el-button
          >
          <el-button
            v-if="
              pageOpersFn('OPERATE_ALLOCATE_WITNESS_USER', scope.row.pageOpers)
            "
            type="text"
            size="default"
            @click="allocateClickFn(scope)"
            >分配见证人</el-button
          >
          <el-button
            v-if="
              pageOpersFn('OPERATE_ENTRY_WITNESS_SUB_TASK', scope.row.pageOpers)
            "
            type="text"
            size="default"
            @click="enterClickFn(scope)"
            >进入见证</el-button
          >
          <el-button
            v-if="
              pageOpersFn('OPERATE_START_SUB_WITNESS_TASK', scope.row.pageOpers)
            "
            type="text"
            size="default"
            @click="startClickFn(scope)"
            >开始见证</el-button
          >
          <el-button
            v-if="
              pageOpersFn('OPERATE_TRANSFER_WITNESS_USER', scope.row.pageOpers)
            "
            type="text"
            size="default"
            @click="allocateUserClickFn(scope)"
            >移交见证</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>
    <!-- 见证记录 -->
    <!-- <WitnessRecord
      :show="recordShow"
      :type="recordType"
      :id="subtaskRow.witnessSubTaskId"
      :rowData="currentWitness"
      :initData="TASKOBJ"
      @close="recordCloseFn"
      @submit="recordSubmitFn"
    /> -->
    <WitnessRecord
      :id="currentWitness.witnessSubTaskId"
      :show="recordShow"
      :type="recordType"
      :header-title="recordTitle"
      :row-data="currentWitness"
      :data="recordData"
      :init-data="TASKOBJ"
      @close="recordCloseFn"
      @submit="recordSubmitFn"
    />
    <!-- 暂停记录弹框 currProjectData-->
    <vStopRecord
      :init-data="TASKOBJ"
      type="read"
      :id="currentWitness.witnessSubTaskId"
      :visible.sync="stopRecordVisible"
      :show="stopRecordVisible"
      @close="closeStopRecordDialogFn"
    />
    <!-- 移交见证 -->
    <el-dialog title="移交见证" :visible.sync="yiJiaoVisible" width="500" draggable custom-class="dialog-demo">
      <div>
        <span class="warning">!</span>
        移交见证任务后该任务将从当前列表中移除，请确认无误后进行移交。
      </div>
      <el-form ref="formSubt" :model="formSubt" label-width="auto" label-max-width="140px" :rules="rulesyj">
        <el-form-item label="移交给" prop="witnessSubTaskIdList">
          <el-select v-model="formSubt.witnessSubTaskIdList" placeholder="请选择" @change="yiJiaoChange">
            <el-option v-for="(item, index) in subtaskList" :key="index" :label="item.userName" :value="item.userId" />
          </el-select>
        </el-form-item>
        <el-form-item label="移交原因" prop="reason">
          <el-input
            v-model="formSubt.reason"
            type="textarea"
            placeholder="请输入移交原因"
            :rows="4"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        <el-form-item class="dialog-footer">
          <span>
            <el-button type="primary" @click="submitYj('formSubt')">确定</el-button>
            <el-button @click="cancelYj('formSubt')">取消</el-button>
          </span>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="结束见证" :visible.sync="finishVisible" width="500px" class="cancel-dialog">
      <div class="info-box">
        <i class="el-icon-warning font-orange" />
        请确认当前见证的交易活动已结束，确认无误后进行结束见证操作。
        <br />
        <br />
        结束见证时将自动执行见证事项【确认】操作。
        <br />
        结束见证后当前见证子任务可在1小时内再次开启见证。
      </div>
      <span slot="footer">
        <el-button type="primary" :loading="cancelLoading" @click="submitCodeDialogFn">确定</el-button>
        <el-button @click="closeCodeDialogFn">取消</el-button>
      </span>
    </el-dialog>
    <!-- 项目详情弹窗 -->
    <!-- <ProjectDetailsDialog :visible.sync="detailDialogShow" :projectId="currentProjectId" :taskObj="TASKOBJ" /> -->
    <ProjectDetailsDrawer
      :visible.sync="detailDialogShow"
      @closeDrawer="closeDrawerFn"
      :project-id="currentProjectId"
      :task-obj="TASKOBJ"
    />
  </div>
</template>
<script>
import { FindArrayFn as findArrayFn, formatDateFn } from "../../../utils/utils";
import WitnessRecord from "../../../components/dialog/WitnessRecord.vue";
import vStopRecord from "../../../components/dialog/StopRecord.vue";
// import ProjectDetailsDialog from "../../../components/dialog/ProjectDetailsDialog.vue";
import ProjectDetailsDrawer from "../../../components/dialog/ProjectDetailsDrawer.vue";
import {
  subtaskStart,
  subtaskFinish,
  subtaskAllocateUser,
  subtaskPermissionUser,
  subtaskCancelFinished
} from "../../../api/api.js";

import { GZAPI_EvaluationTime } from "../../../../gz_plugin/api";
import gzOverWitness from "../../../../gz_plugin/components/gz-over-witness";
import gzAddReviewTime from "../../../../gz_plugin/components/gz-add-review-time";


export default {
  name: "TaskTable",
  components: { WitnessRecord, vStopRecord, ProjectDetailsDrawer, gzOverWitness, gzAddReviewTime },
  props: {
    witnessLinkCode: {
      type: String,
      default: ""
    },
    tableData: {
      type: Array,
      default() {
        return [];
      }
    },
    // eslint-disable-next-line vue/prop-name-casing
    TASKOBJ: {
      type: Object,
      default() {
        return {};
      }
    },
    currentPage: {
      type: Number,
      default: 1
    },
    pageSize: {
      type: Number,
      default: 10
    },
    selection: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      expandRowKeys: [],
      subtaskList: [],
      recordData: [],
      recordShow: false,
      allocateVisible: false,
      yiJiaoVisible: false,
      finishVisible: false,
      cancelLoading: false,
      stopRecordVisible: false, // 暂停弹框
      witnessSubTaskId: "", // 暂停弹框
      recordType: "",
      recordTitle: "",
      currentWitness: {},
      currentProject: [],
      currentIndex: 0,
      currentRowIndex: 0,
      subtaskRow: {},
      tableTaskList: [],
      rulesyj: {
        witnessSubTaskIdList: [{ required: true, message: "移交人不能为空", trigger: "blur" }],
        reason: [{ required: true, message: "移交原因不能为空", trigger: "blur" }]
        // witnessSubTaskIdList: [
        //   { required: true, message: "事项说明不能为空", trigger: "change" },
        // ],
      },
      formSubt: {
        witnessSubTaskIdList: "",
        reason: "",
        userId: ""
      },
      mergeColumns: [
        {
          key: "bidSectionName",
          conditions: ["bidSectionName"]
        },
        {
          key: "bidSectionCode",
          conditions: ["bidSectionCode"]
        },
        {
          key: "bidOpenStartTime",
          conditions: ["bidSectionName", "bidOpenStartTime"]
        },
        {
          key: "openAddress",
          conditions: ["bidSectionName", "openAddress"]
        },
        {
          key: "evaluationAddress",
          conditions: ["bidSectionName", "evaluationAddress"]
        }
      ],
      detailDialogShow: false, // 是否展示项目详情弹窗
      currentProjectId: "" // 当前操作的项目id
    };
  },
  watch: {
    tableData(val) {
      this.tableTaskList = val;
    }
  },

  deactivated(){
    this.setExpandRowKeys('close')
  },
  methods: {
    // 展开
    setExpandRowKeys(item) {
      const projectId = item.projectId || projectId;
      const index = this.expandRowKeys.indexOf(projectId);
      if (item === 'close') {
        this.expandRowKeys = [];
      } else if (index === -1) {
        this.expandRowKeys.push(projectId);
      } else if(index > -1) {
        this.expandRowKeys.splice(index, 1);
      }
    },


    // 查看见证报告
    goToWitnessReport(product) {
      sessionStorage.setItem('have-param', JSON.stringify(this.$parent.formSearch))
      this.$router.push({
        path: "WitnessReport",
        query: {
          projectCode: product.projectCode
        }
      });
    },
    /**
     * 项目级别开始见证
     * @param type KB: '开标', PB: '评标',
     */
    async startAllClickFn(type, { projectId }) {
      try {
        const { code, message, data } = await GZAPI_EvaluationTime.subtaskAllStart({
          projectId,
          type
        });

        if (code === 0) {
          if (!data.errorbidSectionNames || data.errorbidSectionNames.length === 0) {
            this.$message({
              type: "success",
              message: "操作成功",
              single: true
            });
            this.$emit("pagination");
          } else {
            this.$message({
              type: "error",
              message:
                <div>开始见证失败: {data.errorbidSectionNames.join(",")}<br />失败原因:{data.errorMsg}</div>,
              single: true
            });
          }
        } else {
          this.$message({
            type: "error",
            message: "message" || "获取数据失败，请稍后再试",
            single: true
          });
        }
      } catch (e) {
        console.error(e);
      }
    },

    // 项目级别结束见证
    async finishAllClickFn(type, { projectId }, closeFun) {
      try {
        const { code, message, data } = await GZAPI_EvaluationTime.subtaskAllFinish({
          projectId,
          type
        });

        if (code === 0) {
          if (!data.errorbidSectionNames || data.errorbidSectionNames.length === 0) {
            this.$message({
              type: "success",
              message: "操作成功",
              single: true
            });
            if (closeFun instanceof Function) {
              closeFun();
            }
            this.$emit("pagination");
          } else {
            this.$message({
              type: "error",
              message:
                <div>结束见证失败:{data.errorbidSectionNames.join(",")}<br />失败原因:{data.errorMsg}</div>,
              single: true
            });
          }
        } else {
          this.$message({
            type: "error",
            message: "message" || "获取数据失败，请稍后再试",
            single: true
          });
        }
      } catch (e) {
        console.error(e);
      }
    },

    ...{ formatDateFn },
    closeDrawerFn() {
      console.log("closeDrawerFn");
      this.currentProjectId = "";
      this.detailDialogShow = false;
    },
    pageOpersFn(val, Arr) {
      return Arr.some((item) => item.code === val);
    },
    indexFn(index) {
      return index + 1 + (this.currentPage - 1) * this.pageSize;
    },
    recordCloseFn() {
      this.recordShow = false;
      this.recordTitle = "";
    },
    recordSubmitFn() {
    },
    // 项目详情
    handleViewDetailFn(projectId) {
      this.currentProjectId = projectId;
      this.detailDialogShow = true;
    },
    recordShowFn({ row }) {
      console.log("row", row);
      this.currentWitness = row.data;
      this.recordShow = true;
      this.recordTitle = "查看见证记录";
    },
    // 进入见证
    enterClickFn({ row }) {
      this.$router.push({
        name: "Workbench",
        query: { id: row.witnessSubTaskId }
      });
    },
    // 开始见证
    startClickFn({ row, $index }) {
      console.log("row", row);
      this.currentWitness = row;
      this.currentWitness.index = $index;
      this.subtaskStartFn();
    },
    // 开始见证
    async subtaskStartFn() {
      const p = { witnessSubTaskId: this.currentWitness.witnessSubTaskId };
      try {
        const res = await GZAPI_EvaluationTime.subtaskStart(p);
        if (res.success) {
          this.$message({
            type: "success",
            message: "操作成功",
            single: true
          });
          this.$router.push({
            name: "Workbench",
            query: {
              id: this.currentWitness.witnessSubTaskId
            }
          });
          // this.$set(
          //   this.tableTaskList[this.currentWitness.index].pageOpers[i],
          //   "code",
          //   "OPERATE_ENTRY_WITNESS_SUB_TASK"
          // );
        } else {
          this.$message({
            type: "error",
            message: res.message || "获取数据失败，请稍后再试",
            single: true
          });
        }
      } catch (err) {
        console.error(err);
        this.$message({
          type: "error",
          message: "获取数据失败，请稍后再试",
          single: true
        });
      }
    },
    // 结束见证弹框事件
    submitCodeDialogFn() {
      this.finishVisible = false;
      this.subtaskFinishFn();
    },
    closeCodeDialogFn() {
      this.finishVisible = false;
      this.cancelLoading = false;
    },
    //结束见证
    async subtaskFinishFn() {
      const p = {
        witnessSubTaskId: this.currentWitness.witnessSubTaskId
      };
      try {
        const res = await GZAPI_EvaluationTime.finish(p);
        if (res.success) {
          this.$message({
            type: "success",
            message: res.message || "操作成功",
            single: true
          });
          this.deleteCurrentBidFn();
          // this.$parent.handleSearchFn();
          this.formSubt = {};
        } else {
          this.$message({
            type: "error",
            message: res.message || "获取数据失败，请稍后再试",
            single: true
          });
        }
      } catch (err) {
        console.error(err);
        this.$message({
          type: "error",
          message: "获取数据失败，请稍后再试",
          single: true
        });
      }
    },
    // 移交见证
    async subtaskAllocateFn(row) {
      this.yiJiaoVisible = true;
      const p = {
        witnessSubTaskIdList: [row.witnessSubTaskId]
      };
      try {
        const res = await subtaskPermissionUser(p);
        if (res.success) {
          this.subtaskList = res.data.data;
        } else {
          this.$message({
            type: "error",
            message: res.message || "获取数据失败，请稍后再试",
            single: true
          });
        }
      } catch (err) {
        console.error(err);
        this.$message({
          type: "error",
          message: "获取数据失败，请稍后再试",
          single: true
        });
      }
    },
    cancelYj(formSubt) {
      this.$refs[formSubt].resetFields();
      this.formSubt.witnessSubTaskIdList = "";
      this.yiJiaoVisible = false;
    },
    submitYj(formSubt) {
      this.$refs[formSubt].validate((valid) => {
        if (valid) {
          this.subtaskAllocateUserFn();
          this.yiJiaoVisible = false;
        } else {
          return false;
        }
      });
    },
    yiJiaoChange(e) {
      this.formSubt.userId = e;
    },
    async subtaskAllocateUserFn() {
      const isAllocateAllUser = this.isAllocateAllUser || false;
      console.log(this.currentWitness);
      const p = {
        userId: this.formSubt.userId,
        reason: this.formSubt.reason,
        witnessSubTaskAllocateType: "TRANSFER_ALLOCATE"
      };

      if (isAllocateAllUser) {
        p.witnessSubTaskIdList = this.currentProject.map(it => it.witnessSubTaskId);
      } else {
        p.witnessSubTaskIdList = [this.currentWitness.witnessSubTaskId];
      }

      try {
        const res = await subtaskAllocateUser(p);
        if (res.success) {
          this.$message({
            type: "success",
            message: "移交成功",
            single: true
          });
          this.yiJiaoVisible = false;
          if (isAllocateAllUser) {
            this.$emit("pagination");
          } else {
            this.deleteCurrentBidFn();
          }

          // this.$parent.handleSearchFn();
          this.formSubt = {};
        } else {
          this.$message({
            type: "error",
            message: res.message || "获取数据失败，请稍后再试",
            single: true
          });
        }
      } catch (err) {
        console.error(err);
        this.$message({
          type: "error",
          message: "获取数据失败，请稍后再试",
          single: true
        });
      }
    },
    deleteCurrentBidFn() {
      // 只剩下一个标段时点击移交或者结束见证当前项目从列表中删除
      if (this.currentProject.length === 1) {
        this.tableTaskList.splice(this.currentRowIndex, 1);
        return;
      }
      for (const [index] of this.currentProject.entries()) {
        if (index === this.currentIndex) {
          this.currentProject.splice(index, 1);
        }
      }
    },
    // 项目级别 移交见证
    async allocateAllUserClickFn(row) {
      this.currentProject = row.bidsectionInfoList;
      // 是否是移交项目下所有的标段
      this.isAllocateAllUser = true;
      this.yiJiaoVisible = true;
      const p = {
        witnessSubTaskIdList: row.bidsectionInfoList.map(item => item.witnessSubTaskId)
      };
      try {
        const res = await subtaskPermissionUser(p);
        if (res.success) {
          this.subtaskList = res.data.data;
          this.$emit("pagination");
        } else {
          this.$message({
            type: "error",
            message: res.message || "获取数据失败，请稍后再试",
            single: true
          });
        }
      } catch (err) {
        console.error(err);
        this.$message({
          type: "error",
          message: "获取数据失败，请稍后再试",
          single: true
        });
      }
    },
    // 标段 移交见证
    allocateUserClickFn({ row, $index }, props) {
      this.currentWitness = row;
      this.currentProject = props.row.bidsectionInfoList;
      this.currentIndex = $index;
      this.subtaskAllocateFn(row);
    },
    finishWitnessFn({ row, $index }, props) {
      this.currentWitness = row;
      this.currentProject = props.row.bidsectionInfoList;
      this.currentIndex = $index;
      this.currentRowIndex = props.$index;
      this.finishVisible = true;
    },
    stopRecordFn({ row }, props) {
      console.log("row", row);
      console.log("props", props);
      this.currentWitness = row;
      // this.currentProject = props.row.bidsectionInfoList;
      // this.currentIndex = $index;
      // this.currentRowIndex = props.$index;
      // this.currProjectData = row;
      this.stopRecordVisible = true;
    },
    revokeWitnessFn({ row, $index }, props) {
      console.log("row", row);
      console.log("props", props);
      this.currentWitness = row;
      this.currentProject = props.row.bidsectionInfoList;
      this.currentIndex = $index;
      this.$confirm("是否对该标段见证环节进行撤销操作？", "撤销见证", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.subtaskCancelFinishedFn();
        })
        .catch(() => {
        });
    },
    async subtaskCancelFinishedFn() {
      console.log(this.currentWitness);
      const p = {
        witnessSubTaskId: this.currentWitness.witnessSubTaskId
      };
      try {
        const res = await subtaskCancelFinished(p);
        if (res.success) {
          this.$message({
            type: "success",
            message: "撤销成功",
            single: true
          });
          // this.yiJiaoVisible = false;
          this.deleteCurrentBidFn();
          // this.$parent.handleSearchFn();
          this.formSubt = {};
        } else {
          this.$message({
            type: "error",
            message: res.message || "获取数据失败，请稍后再试",
            single: true
          });
        }
      } catch (err) {
        console.error(err);
        this.$message({
          type: "error",
          message: "获取数据失败，请稍后再试",
          single: true
        });
      }
    },
    // 关闭暂停见证
    closeStopRecordDialogFn() {
      this.stopRecordVisible = false;
    },
    tenderModeFn(val) {
      const array = this.TASKOBJ.industryTypeAndTenderMode;
      const obj = findArrayFn(array, val) || {};
      return obj.label;
    },
    // 任务状态
    witnessSubTaskStatusFn(val) {
      const array = this.TASKOBJ.witnessSubTaskStatus;
      const obj = findArrayFn(array, val) || {};
      return obj.label;
    },
    witnessItemStatusFn(val) {
      const array = this.TASKOBJ.witnessItemStatus;
      const obj = findArrayFn(array, val) || {};
      return obj.label;
    },
    // 行业类型转文字
    industryFn(val) {
      const array = this.TASKOBJ.industryTypeAndIndustry;
      const obj = findArrayFn(array, val) || {};
      return obj.label;
    },
    // 行业子类型转文字
    subIndustryFn(val) {
      const array = this.TASKOBJ.industryAndTenderMode;
      const obj = findArrayFn(array, val) || {};
      return obj.label;
    },
    // 交易方式转文字
    industryTypeFn(val, type) {
      const array = this.TASKOBJ.industryTypeAndTenderMode;
      for (const item of array) {
        if (item.value === type) {
          const obj = findArrayFn(item.children, val) || {};
          return obj.label;
        }
      }
    },
    // 见证阶段转文字
    // witnessLinkCodeFn(val, type) {
    witnessLinkCodeFn(val) {
      const array = this.TASKOBJ.taskWitnessLinkAll;
      let a = {};
      a = array.find((item) => item.value === val);
      return a.label;
    },
    // 资审方式转文字
    qualificationExamMethodFn(val) {
      const array = this.TASKOBJ.qualificationExamMethods;
      const obj = findArrayFn(array, val) || {};
      return obj.label;
    },
    // 子任务表格多选
    handleSubTaskSelectionChangeFn(val) {
      console.log("val", val);
      this.multipleSubTaskSelection = val;
      this.assignData = val;
    },
    buildDataStatus(status) {
      switch (status) {
        case "已推送":
          return "dot assign-dot";
        case "未推送":
          return "dot end-dot";
        case "已推送(异常)":
          return "dot start-dot";
      }
    },
    handleClickWitnessRecordFn({ row }, props) {
      sessionStorage.setItem('have-param', JSON.stringify(this.$parent.formSearch))
      this.$router.push({
        name: "ViewingWitnessRecords",
        query: {
          projectId: props.row.projectId,
          bidSectionId: row.bidSectionId,
          witnessLinkCode: row.witnessLinkCode,
          witnessSubTaskName: row.witnessSubTaskName,
          witnessSubTaskId: row.witnessSubTaskId,
          witnessSubTaskStatusEnum: row.witnessSubTaskStatusEnum,
          urlName: "HaveWitnessed"
        }
      });
    },
    //
    managerFlag() {
      return this.$store.getters.roles.some((item) => item.roleCode === "GDW_R_WITNESS_MANAGER");
      // return this.$store.getters.roleCode==="GDW_R_WITNESS_PERSON"
    },
    openMediaFn(row, scope) {
      // 见证人员-已完成
      console.log("openMediaFn");
      console.log("row", row);
      // console.log("scope", scope);
      // 管理员传子任务id，查看视频
      const { witnessSubTaskId } = row;
      // let videoCreateTime = row.witnessStartTime.split(" ")[0];
      // let startTime = new Date(videoCreateTime + " 00:00:00").getTime();
      // let endTime = new Date(videoCreateTime + " 23:59:59").getTime();
      let str = new Date().getTime();
      str += `&witnessSubTaskId=${witnessSubTaskId}`;
      str += "&type=over";
      // str += `&startTime=${startTime}&endTime=${endTime}`;
      console.log("flag", str);
      window.open(`${process.env.VUE_APP_MEDIA}${str}`, "witness_media");
    },
    handleClickAttachment({ row }, props) {
      const attachmentList = [];
      console.log("row", row);
      console.log("props", props);
      for (const item of props.row.bidsectionInfoList) {
        console.log("item.pageOpers", item.pageOpers);
        const flagcode = item.pageOpers.some((itemB) => itemB.code === "OPERATE_VIEW_WITNESS_ATTACHMENT");
        if (flagcode && item.bidSectionName === row.bidSectionName) {
          console.log("item", item);
          attachmentList.push({
            witnessSubTaskName: item.witnessSubTaskName,
            bidSectionId: item.bidSectionId,
            witnessSubTaskId: item.witnessSubTaskId,
            witnessLinkCode: item.witnessLinkCode
          });
        }
      }
      this.$router.push({
        path: "/WitnessTask/Attachment",
        query: {
          attachmentList: JSON.stringify(attachmentList),
          // currentStage: row.witnessLinkCode,
          witnessSubTaskName: row.witnessSubTaskName,
          from: "attachment",
          projectName: props.row.projectName,
          bidSectionName: row.bidSectionName
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.warning {
  width: 20px;
  height: 20px;
  display: inline-block;
  background: #e6ad00;
  color: #fff;
  text-align: center;
  border-radius: 50%;
  margin-right: 5px;
  margin-bottom: 20px;
}

.dialog-footer {
  text-align: right;
}

.dot {
  width: 10px;
  height: 10px;
  display: inline-block;
  border-radius: 5px;
  margin-right: 6px;
  margin-top: 0px;
  margin-bottom: -1px;
}

.end-dot {
  background: $end-dot;
}

.start-dot {
  background: $start-dot;
}

.assign-dot {
  background: $assign-dot;
}

.result-icon-container {
  display: inline-block;
  width: 72px;
  height: 20px;
  font-size: 12px;
  line-height: 20px;
  text-align: center;
  border-radius: 2px;
}

.result-icon-container.normal {
  color: #66bc1a;
  background: rgba(102, 188, 26, 0.1);
  border: 1px solid rgba(151, 151, 151, 0.2);
}

.result-icon-container.unnormal {
  color: #fc9306;
  background: rgba(252, 147, 6, 0.1);
  border: 1px solid rgba(252, 147, 6, 0.3);
}

.finish-all-click {

}
</style>
